package com.youhong.teethcare

import android.app.ProgressDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.youhong.cuptime.blesdk.BleService
import com.youhong.teethcare.netbeans.OtaHttpReturn
import com.youhong.teethcare.ryan.DfuTool
import com.youhong.teethcare.services.Common
import com.youhong.teethcare.utils.DialogUtil
import com.youhong.teethcare.utils.HttpJsonUtils2
import com.youhong.teethcare.utils.HttpJsonUtils2.downloadCallback
import com.youhong.teethcare.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_firmware_update.*
import org.apache.http.NameValuePair
import org.apache.http.message.BasicNameValuePair
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

class FirmwareUpdateActivity : BaseActivity() ,  DfuTool.DfuStateListener{
    private lateinit var filePath: String
    private lateinit var mDfuTool: DfuTool
    private val TAG = "FirmwareUpdateActivity"
    var hasNewVersion = false;
    lateinit var fileUrl: String;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initStatusBar(resources.getColor(R.color.pageBackground), true)
        setContentView(R.layout.activity_firmware_update)
        firmware_iv_back.setOnClickListener { finish() }
        bt_checkVersion.setOnClickListener {
            //checkFirmwareVersion(0)
        }
        btDownloadFirmware.setOnClickListener {
            when (hasNewVersion) {
                true -> downloadFile()
                else -> {
                    Log.i(TAG, "onCreate: last")
                }
            }
        };
        lastVersionAlreadyState(Common.userInfo.deviceVersion)
        registerReceiver()
        getDeviceVersion()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    fun registerReceiver() {
        val filter = IntentFilter()
        filter.addAction(BleService.ACTION_DATA_AVAILABLE)
        registerReceiver(receiver, filter)
    }

    var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {

            //绑定牙刷进行同步时，1.获取电量 ,2.获取刷牙时长,3.同步历史数据
            val values = intent.getByteArrayExtra(BleService.EXTRA_DATA)
            if (values!![0] == 0x27.toByte()) {
               var firmwareVersion = ((values[1] - 0x30)
                        .toString() + "." + (values[2] - 0x30) + "."
                        + (values[3] - 0x30) + "." + (values[4] - 0x30))
                var deviceVersion = firmwareVersion.replace(".", "");
                checkFirmwareVersion(deviceVersion.toInt())

            }
        }
    }

    fun getDeviceVersion() {
        if (MainActivity.mDevice != null)
            MainActivity.mDevice.getVersion()
        //checkFirmwareVersion();
    }

    fun downloadFile() {
        Log.i(TAG, "downloadFile: downLoad")

        //    Log.e("UIThreadId", "" + Thread.currentThread().getId() + "");
        var storageRootPath = ImageUtils.getOtaPath(this)
         filePath=storageRootPath+ File.separator+fileUrl.substring(fileUrl.lastIndexOf("/") + 1)
        //下载zip升级包
        object : Thread() {
            override fun run() {
                try {
                    HttpJsonUtils2.downloadFile(fileUrl, filePath, download_callback)
                } catch (exp: java.lang.Exception) {
                }
            }
        }.start()
    }

    var download_callback = downloadCallback { isSucess, fileSize ->
        if (isSucess) {
            runOnUiThread(Runnable {

                if (MainActivity.mDevice != null) MainActivity.mDevice.upgradeFirmware()
                startOta()
            })
        }
    }
    var mDialog: ProgressDialog? = null
    fun startOta(){
        if (mDialog == null) {
            mDialog = DialogUtil.showDialog(this, R.string.strings76)
        }
        mDialog?.show()
        mDfuTool = DfuTool(this, filePath, this)
        mDfuTool.startScan(true)
        btDownloadFirmware.text=resources.getString(R.string.strings77)
        btDownloadFirmware.isEnabled=false
    }

    fun checkFirmwareVersion(deviceVersion: Int) {
        object : Thread() {
            override fun run() {
                val params: MutableList<NameValuePair> = ArrayList()
                val deviceName = Common.userInfo.deviceName
                var deviceType = "teethcare"
                if (!TextUtils.isEmpty(deviceName)) {
                    if (deviceName.toLowerCase().contains("fg")) deviceType = "2058"
                }
                params.add(BasicNameValuePair("type", deviceType))

              //  params.add(BasicNameValuePair("version", "000"))

                 params.add(BasicNameValuePair("version", deviceVersion.toString() + ""))
                val mReturn = HttpJsonUtils2.doGetHttpRequest_Sync(HttpJsonUtils2.URL_OTA, params, OtaHttpReturn::class.java)
                try {
                    runOnUiThread(Runnable {
                        mReturn?.let {
                            var code = mReturn.msgCode;
                            var fileInfo = mReturn.data;
                            when (code) {
                                1052 -> findNewVersionState(fileInfo.version, fileInfo.url);
                                else -> lastVersionAlreadyState(Common.userInfo.deviceVersion);
                            }
                        } ?: let {
                            lastVersionAlreadyState(Common.userInfo.deviceVersion);
                            Toast.makeText(this@FirmwareUpdateActivity, R.string.strings30, Toast.LENGTH_SHORT).show()

                        }

                    })
                } catch (exp: Exception) {
                }
            }
        }.start()
    }


    fun findNewVersionState(newVersion: String, fileUrl: String) {
        //tvFileSize.visibility=View.VISIBLE;
        // tvFileSize.text="Size: $fileSize kb"
        this.fileUrl = fileUrl;
        hasNewVersion = true;
        tvNewVersion.text = getString(R.string.strings73)
        tvFindNewVersion.visibility = View.VISIBLE
        tvVersionName.text = "V $newVersion";
        bt_checkVersion.text = newVersion;
        btDownloadFirmware.text = getString(R.string.strings74)
        btDownloadFirmware.isEnabled = true
        btDownloadFirmware.setTextColor(Color.WHITE)
        ivNewVersionTips.visibility = View.VISIBLE
        Common.serverFirmwareVersion=newVersion
    }

    fun lastVersionAlreadyState(currentVersion: String) {
        hasNewVersion = false;
        tvNewVersion.text = getString(R.string.Current_version_number)
        tvVersionName.text = "V $currentVersion";
        tvFileSize.visibility = View.GONE
        tvFindNewVersion.visibility = View.INVISIBLE
        bt_checkVersion.text = currentVersion;
        btDownloadFirmware.text = getString(R.string.strings72)
        btDownloadFirmware.isEnabled = false
        btDownloadFirmware.setTextColor(Color.BLACK)
        ivNewVersionTips.visibility = View.GONE
    }

    fun updateOtaProgress(stateCode:Int) {
        if(mDialog!!.isShowing) mDialog!!.dismiss()
        updateProgressCircle.update(stateCode/100f)
        bt_checkVersion.text="$stateCode%"
    }

    override fun onStateChange(stateCode: Int) {
        if (stateCode == DfuTool.PROGRESS_READY) {
            //mDialog!!.dismiss()
        } else if (stateCode == DfuTool.PROGRESS_DFU_PREPARE) {
            //mDialog!!.dismiss()

        } else if (stateCode == DfuTool.PROGRESS_FAILED) {
            if(mDialog!!.isShowing) mDialog!!.dismiss()
            mDialog = null
            Toast.makeText(this, R.string.strings80, Toast.LENGTH_SHORT).show()
        } else if (stateCode == DfuTool.PROGRESS_FINISHED) {
            if(mDialog!!.isShowing) mDialog!!.dismiss()
            mDialog = null
            lastVersionAlreadyState(Common.serverFirmwareVersion)
        } else {
            updateOtaProgress(stateCode)
        }
    }


}